﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Apparat.Renderables.AssimpMeshInterface
{
    public class AssimpModel : Renderable
    {
        public AssimpMesh[] AssimpMesh;
        public Assimp.Material[] AssimpMaterial;
        public Assimp.Node Root;


        public override void Render()
        {
            if (AssimpMesh.Length > 0)
            {
                RenderNode(Root);
            }


        }

        protected SlimDX.Matrix globalTransform = SlimDX.Matrix.Identity;

        public void RenderNode(Assimp.Node node)
        {
            if (node.HasMeshes)
            {
                foreach (int meshIndex in node.MeshIndices)
                {
                    AssimpMesh[meshIndex].Transform = SlimDX.Matrix.Identity;
                    SlimDX.Matrix transform = SlimDX.Matrix.Identity;

                    Assimp.Node searchNode = node;
                    while (searchNode != null)
                    {
                        SlimDX.Matrix nodeTransform = AssimpAux.ToSlimDXMatrixTransposed(searchNode.Transform);
                        transform = transform * nodeTransform;
                        searchNode = searchNode.Parent;
                    }

                    //AssimpMesh[meshIndex].Transform = transform;
                    AssimpMesh[meshIndex].Transform = transform * globalTransform;
                    AssimpMesh[meshIndex].Render();
                }
            }

            if (node.HasChildren)
            {
                foreach (Assimp.Node child in node.Children)
                {
                    RenderNode(child);
                }
            }
        }

        public override void Dispose()
        {
            foreach (AssimpMesh mesh in AssimpMesh)
            {
                mesh.Dispose();
            }
        }

        public override SlimDX.Matrix Transform
        {
            get
            {
                return AssimpAux.ToSlimDXMatrixTransposed(Root.Transform);
            }
            set
            {
                globalTransform = value;
            }
        }
    }
}
